package modbus.com.serialport;

import com.alibaba.fastjson.JSONObject;
import modbus.com.domain.MeterCounterIot;
import modbus.com.service.MeterCounterIotService;
import modbus.com.util.HexUtils;
import modbus.com.websocket.WebSoceketLightBoard;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 串口通讯下发解析
 * @autho
 */
@Component
public class SerialPortSend {
    @Resource
    private MeterCounterIotService iotService;
    //  portName COM名称
    //  data 报文
    //  baudRate 波特率
    //  dataBits 数据位
    //  stopBits 停止位
    //  parity 校验
    public static void send(String portName, String data, Integer baudRate, int dataBits, int stopBits, int parity) throws InterruptedException {
        SerialPortManager.connectSerialPort(portName, baudRate, dataBits, stopBits, parity);
        //像串口传数据
        if (SerialPortManager.SERIAL_PORT_STATE) {
            SerialPortManager.sendSerialPortData(HexUtils.hexStrToBytes(data));
        }
        //等待500毫秒
        Thread.sleep(500);
        //关闭串口
        SerialPortManager.closeSerialPort();
    }
    //定时轮训数据
    @Scheduled(fixedDelay = 1000)
    public void start() throws InterruptedException {
        //数据库里查询的串口列表
        List<MeterCounterIot> meterCounterIotList = iotService.list();
        for (MeterCounterIot meterCounterIot : meterCounterIotList) {
            send(meterCounterIot.getConPort(), meterCounterIot.getMessage(), meterCounterIot.getBaudRate(), meterCounterIot.getDataBits(), meterCounterIot.getStopBits(), meterCounterIot.getParity());
        }
    }
    //监听串口返回的数据
    public void dataAvailable() {
        try {
            //当前监听器监听到的串口返回数据
            byte[] back = SerialPortManager.readSerialPortData();
            String message = HexUtils.bytesToHexStr(back);
            System.out.println("收到设备返回的数据----->>" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())) + message);
            dispose(message);
        } catch (Exception e) {
            System.out.println(e.toString());
        }

    }
    //处理报文
    public void dispose(String hexData) {
        //去掉报文头
        String toTop = hexData.substring(6, hexData.length());
        //去掉尾部校验
        String toTrail = toTop.substring(0, toTop.length() - 4);
        //数据位16进制转10进制结果
        Integer count = decodeHEX(toTrail);
        //在数字后两位前插入小数点
        StringBuilder stringBuilder = new StringBuilder(count.toString());
        //添加小数点
        stringBuilder.insert(count.toString().length() - 2, ".");
        System.out.println(decodeHEX(hexData.substring(0, 2)) + "号设备采集数据----->>" + stringBuilder);
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("piont",decodeHEX(hexData.substring(0,2)));
        jsonObject.put("meter",stringBuilder);
        //socket通讯
          WebSoceketLightBoard.sendTextMessage(jsonObject.toJSONString());
    }

    //将16进制的数转换为10进制 输入的是16进制
    public static int decodeHEX(String hexs) {
        //hexs 表示是16进制的数
        BigInteger bigInteger = new BigInteger(hexs, 16);
        int value = bigInteger.intValue();
        return value;
    }
}
